<template>
  <d2-container>
    <el-card shadow="never" class="d2-mb">
      <el-form class="filter-container" label-width="85px">
        <el-row :gutter="20" style="height:30px">
          <!-- <el-col :span="5">
            <el-form-item label="机构名称">
              <el-select
                v-model="searchData.name"
                placeholder="请选择"
                filterable
                style="width:100%;"
                @change="handle_band"
                clearable
              >
                <el-option
                  v-for="item in selectNameList"
                  :key="item.name"
                  :label="item.name"
                  :value="item.name"
                >
                  <span style="float: left">{{ item.name }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :span="5">
            <el-form-item label="部门名称" prop="department">
              <el-select
                v-model="searchData.department"
                placeholder="请选择"
                style="width:100%;"
                clearable
              >
                <el-option
                  v-for="item in selectDepartsList"
                  :key="item.department_name"
                  :label="item.name"
                  :value="item.department_name"
                >
                  <span style="float: left">{{ item.name }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="年度计划ID">
              <el-input
                placeholder="请输入内容"
                v-model="searchData.id"
                clearable
                type="number"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="状态">
              <el-select
                v-model="searchData.status"
                placeholder="请选择"
                style="width:100%;"
                clearable
              >
                <el-option label="草拟" value="0"></el-option>
                <el-option label="审核中" value="1"></el-option>
                <el-option label="已驳回" value="2"></el-option>
                <el-option label="已退审" value="3"></el-option>
                <el-option label="已通过" value="4"></el-option>
                <el-option label="已失效" value="5"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="创建人">
              <el-input
                placeholder="请输入内容"
                v-model="searchData.creator"
                clearable
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="开始日期">
              <el-date-picker
                v-model="searchData.startDate"
                type="date"
                placeholder="选择日期"
                style="width:100%;"
                value-format="yyyy-MM-dd"
                clearable
                :picker-options="startDatePicker"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="结束日期">
              <el-date-picker
                v-model="searchData.endDate"
                type="date"
                placeholder="选择日期"
                style="width:100%;"
                value-format="yyyy-MM-dd"
                clearable
                :picker-options="endDatePicker"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-button
              type="primary"
              size="mini"
              @click="search"
              style="margin-top:5px"
            >
              <d2-icon name="search" /> 查询
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <div class="mb">
      <el-button type="default" size="mini" @click="add()">
        <d2-icon name="plus" />
        新增
      </el-button>
      <el-button type="default" size="mini" @click="edit('alter')">
        <d2-icon name="edit" />
        修改
      </el-button>
      <el-button type="default" size="mini" icon="el-icon-delete" @click="del">
        删除
      </el-button>
      <el-button type="default" size="mini" @click="edit('check')">
        <d2-icon name="search" />
        查看
      </el-button>
      <el-button type="default" size="mini" @click="edit('copy')">
        <d2-icon name="clone" />
        复制
      </el-button>
      <el-button type="default" size="mini" @click="submitApproval">
        <d2-icon name="upload" />
        提交审批
      </el-button>
      <el-button type="default" size="mini" @click="retired">
        <d2-icon name="reply" />
        退审
      </el-button>
      <el-button type="default" size="mini" @click="historicalApproval">
        <d2-icon name="history" />
        审批历史
      </el-button>
      <el-button type="default" size="mini" @click="edit('change')">
        <d2-icon name="exchange" />
        变更
      </el-button>
      <el-upload
        class="upload-btn"
        :action="uploadUrl"
        accept=".xls, .xlsx"
        :on-success="handleAvatarSuccess"
        :on-progress="uploadProgress"
        :on-error="handleUploadError"
        :show-file-list="false"
        style="display:inline-block;margin:0 10px;"
      >
        <el-button type="default" size="small">
          <d2-icon name="download" />
          导入
        </el-button>
      </el-upload>
      <el-button type="default" size="mini" @click="Export_fn()">
        <d2-icon name="upload" />
        导出
      </el-button>
      <el-button type="default" size="mini" @click="refresh()">
        <d2-icon name="refresh" />
        刷新
      </el-button>
    </div>
    <el-card shadow="never" class="d2-mb">
      <el-table
        :data="tableData"
        border
        :cell-style="{ 'text-align': 'center' }"
        :header-cell-style="{
          background: '#eef1f6',
          'text-align': 'center',
          color: '#606266'
        }"
        highlight-current-row
        @row-click="handleSelectionChange"
      >
        <el-table-column type="index" label="序号"> </el-table-column>
        <el-table-column prop="status_name" label="状态"></el-table-column>
        <el-table-column
          prop="org_name"
          label="机构名称"
          :formatter="orgFormat"
        ></el-table-column>
        <el-table-column
          prop="department_name"
          label="部门名称"
        ></el-table-column>
        <el-table-column
          prop="id"
          label="年度计划ID"
          sortable
        ></el-table-column>
        <el-table-column prop="name" label="年度计划名称"></el-table-column>
        <el-table-column
          prop="plan_year"
          label="年度计划年度"
          sortable
        ></el-table-column>
        <el-table-column
          prop="start_date"
          label="开始日期"
          sortable
        ></el-table-column>
        <el-table-column
          prop="end_date"
          label="结束日期"
          sortable
        ></el-table-column>
        <el-table-column prop="creator_name" label="创建人"></el-table-column>
        <el-table-column
          prop="created_time"
          label="创建时间"
          sortable
        ></el-table-column>
      </el-table>
    </el-card>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="searchData.page"
      :page-size="searchData.pageSize"
      layout="total, prev, pager, next"
      :total="searchData.totalPage"
    >
    </el-pagination>
  </d2-container>
</template>

<script>
import { getDepartments } from "@/api/url.js";
import { annualPlan } from "@/api/url_info.js";
import { editAnnualPlan } from "@/api/url_info.js";
import { approval } from "@/api/url_info.js";
export default {
  //年度计划
  name: "plan_index",
  components: {},
  data() {
    return {
      startDatePicker: this.beginDate(),
      endDatePicker: this.processDate(),
      dialogVisible: false,
      historicalApprovals: false,
      submitApprovals: false,
      radioType: 1,
      row: "",
      tableData: [],
      spotDatas: [],
      futureDatas: [],
      selectDepartsList: [],
      searchData: {
        page: 1, //当前页
        pageSize: 20,
        totalPage: 0,
        org_name: "",
        department: "",
        id: "",
        status: "",
        startDate: "",
        endDate: "",
        creator: ""
      },
      // 表格选中row数据
      multipleSelection: {}
    };
  },
  created: function() {
    this.annualPlan();
    this.handle_getDepartments();
  },
  methods: {
    // 机构
    orgFormat(row, column) {
      return row.org_name == null ? row.department_name : row.org_name;
    },
    // 清空当前页缓存并刷新此页面
    refresh() {
      this.searchData.searchData = "";
      this.searchData.org_name = "";
      this.searchData.startDate = "";
      this.searchData.creator = "";
      this.searchData.status = "";
      this.searchData.department = "";
      this.searchData.id = "";
      this.searchData.endDate = "";
      this.multipleSelection = "";
      this.annualPlan();
    },
    // 查询部门
    handle_getDepartments() {
      getDepartments()
        .then(res => {
          this.selectDepartsList = [];
          var data1 = res.result;
          var arr = this.treeToList(data1);
          for (var i = 0; i < arr.length; i++) {
            this.selectDepartsList[i] = {
              name: arr[i]["name"],
              department_name: arr[i]["id"]
            };
          }
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },
    //树形结构转换为扁平数组
    treeToList(tree) {
      var queen = [];
      var out = [];
      queen = queen.concat(tree);
      while (queen.length) {
        var first = queen.shift();
        if (first.sub_depart) {
          queen = queen.concat(first.sub_depart);
          delete first["sub_depart"];
        }
        out.push(first);
      }
      return out;
    },
    //这里是控制结束日期不能小于开始日期
    beginDate() {
      const self = this;
      return {
        disabledDate(time) {
          if (self.searchData.endDate) {
            //如果结束时间不为空，则小于结束时间
            return new Date(self.searchData.endDate).getTime() < time.getTime();
          } else {
            // return time.getTime() > Date.now()//开始时间不选时，结束时间最大值小于等于当天
          }
        }
      };
    },
    processDate() {
      const self = this;
      return {
        disabledDate(time) {
          if (self.searchData.startDate) {
            //如果开始时间不为空，则结束时间大于开始时间
            return (
              new Date(self.searchData.startDate).getTime() >
              time.getTime() + 8.64e7
            );
          } else {
            // return time.getTime() > Date.now()//开始时间不选时，结束时间最大值小于等于当天
          }
        }
      };
    },
    //新增
    add() {
      this.$router.push({ path: "/annual_plan/add" });
    },
    // 每页数
    handleSizeChange(val) {
      this.searchData.pageSize = val;
      this.searchData.page = 1;
      this.annualPlan();
    },
    // 当前页
    handleCurrentChange(val) {
      this.searchData.page = val;
      this.annualPlan();
    },
    //提交审批
    submitApproval(row) {
      let objToStr = JSON.stringify(this.multipleSelection);
      if (this.multipleSelection.id) {
        if (this.multipleSelection.status == "已驳回") {
          this.$message({
            message: "已驳回状态不能提交审批",
            type: "warning"
          });
        } else {
          let params = {
            operation: "ADD",
            business_id: this.multipleSelection.id,
            desc: objToStr,
            task: "YPLAN"
          };
          approval(params)
            .then(res => {
              this.annualPlan();
              this.$message({
                message: res.result,
                type: "success"
              });
            })
            .catch(err => {
              this.$message.error(err.msg);
            });
        }
      } else {
        this.$message({
          message: "请选择一条数据",
          type: "warning"
        });
      }
    },
    //审批历史
    historicalApproval(row) {
      if (this.multipleSelection.id) {
        if (this.multipleSelection.workOrderID == "0") {
          this.$message({
            message: "未进入审批历史",
            type: "warning"
          });
        } else {
          this.$router.push(
            "/examine_historyss?id=" + this.multipleSelection.workOrderID
          );
        }
      } else {
        this.$message({
          message: "请选择一条数据",
          type: "warning"
        });
      }
    },
    //退审
    retired() {
      if (this.multipleSelection.id) {
        if (this.multipleSelection.status_name == "审核中") {
          let params = {
            operation: "MOD",
            id: this.multipleSelection.workOrderID,
            status: 3,
            opinion: ""
          };
          approval(params)
            .then(res => {
              this.annualPlan();
              this.$message({
                message: res.result,
                type: "success"
              });
            })
            .catch(err => {
              this.$message.error(err.msg);
            });
        } else {
          this.$message({
            message: "只有状态为“审核中”的信息才能退审",
            type: "warning"
          });
        }
      } else {
        this.$message({
          message: "请选择一条数据",
          type: "warning"
        });
      }
    },
    //查询
    search() {
      this.searchData.page = 1;
      this.annualPlan();
    },
    //网格信息
    annualPlan() {
      annualPlan(this.searchData)
        .then(res => {
          this.tableData = [];
          let data = res.result.results;
          this.searchData.totalPage = res.result.count;
          for (let i = 0; i < data.length; i++) {
            this.tableData[i] = {
              department_name: data[i]["department_name"],
              org_name: data[i]["org_name"],
              status_name: data[i]["status_name"],
              creator_name: data[i]["creator_name"],
              created_time: data[i]["created_time"],
              modified_time: data[i]["modified_time"][i]["modified_time"],
              name: data[i]["name"],
              plan_year: data[i]["plan_year"],
              start_date: data[i]["start_date"],
              end_date: data[i]["end_date"],
              status: data[i]["status"],
              id: data[i]["id"],
              department: data[i]["department"],
              creator: data[i]["creator"],
              workOrderID: data[i]["workOrderID"]
            };
          }
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },
    //选中的一行数据
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //删除
    del() {
      let that = this;
      let data = {
        operation: "DEL",
        plan_info: [that.multipleSelection.id]
      };

      if (that.multipleSelection.id) {
        if (
          that.multipleSelection.status_name == "草拟" ||
          that.multipleSelection.status_name == "已驳回"
        ) {
          that
            .$confirm("是否要删除？", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            })
            .then(() => {
              editAnnualPlan(data)
                .then(res => {
                  that.searchData.page = 1;
                  that.refresh();
                  that.$message({
                    message: res.result,
                    type: "success"
                  });
                })
                .catch(err => {
                  that.$message.error(err.msg);
                });
            });
        } else {
          that.$message({
            message: "只有状态为“草拟”和“已驳回”的信息可以删除",
            type: "warning"
          });
        }
      } else {
        that.$message({
          message: "请选择一条数据",
          type: "warning"
        });
      }
    },
    //编辑信息
    async editInfo(state) {
      let that = this;
      let datas = that.multipleSelection;
      that.$router.push({
        path: "/annual_plan/edit",
        query: { id: datas.id, state: state }
      });
    },
    //修改/查看
    edit(state) {
      let that = this;
      let data = that.multipleSelection;
      if (data.id) {
        if (state == "alter") {
          if (data.status_name == "草拟" || data.status_name == "已驳回") {
            that.editInfo(state);
          } else {
            that.$message({
              message: "只有状态为“草拟”和“已驳回”的信息可以修改",
              type: "warning"
            });
          }
        } else if (state == "change") {
          if (data.status_name == "已通过") {
            that.editInfo(state);
          } else {
            that.$message({
              message: "只有状态为“已通过”的信息可以变更",
              type: "warning"
            });
          }
        } else {
          that.editInfo(state);
        }
      } else {
        that.$message({
          message: "请选择一条数据",
          type: "warning"
        });
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.el-radio {
  width: 100%;
  text-align: center;
  margin-top: 15px;
}
.el-form-item {
  margin-bottom: 15px !important;
}
</style>
